#!/bin/bash

# 文档转换器 - 一键启动脚本 (Linux/macOS)
# 同时启动后端Flask服务器和前端Vite开发服务器

set -e  # 遇到错误时退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${2}${1}${NC}"
}

# 打印标题
print_title() {
    echo -e "\n${CYAN}================================${NC}"
    echo -e "${CYAN}  $1${NC}"
    echo -e "${CYAN}================================${NC}\n"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_message "❌ 错误: $1 未安装或不在PATH中" $RED
        exit 1
    fi
}

# 检查目录是否存在
check_directory() {
    if [ ! -d "$1" ]; then
        print_message "❌ 错误: 目录 $1 不存在" $RED
        exit 1
    fi
}

# 检查文件是否存在
check_file() {
    if [ ! -f "$1" ]; then
        print_message "❌ 错误: 文件 $1 不存在" $RED
        exit 1
    fi
}

# 从config.yaml读取配置信息
read_config() {
    # 读取后端配置
    local config_output
    config_output=$(python3 -c "
import yaml
with open('config.yaml', 'r', encoding='utf-8') as f:
    config = yaml.safe_load(f)
backend_host = config.get('server', {}).get('host')
backend_port = config.get('server', {}).get('port')
frontend_host = config.get('frontend', {}).get('host')
frontend_port = config.get('frontend', {}).get('port')
print(f'{backend_host}:{backend_port}:{frontend_host}:{frontend_port}')
" 2>/dev/null)

    if [ -n "$config_output" ]; then
        IFS=':' read -r SERVER_HOST SERVER_PORT FRONTEND_HOST FRONTEND_PORT <<< "$config_output"
        export SERVER_HOST SERVER_PORT FRONTEND_HOST FRONTEND_PORT
    else
        print_message "❌ 无法读取配置文件" $RED
        exit 1
    fi
}

# 清理函数 - 在脚本退出时杀死子进程
cleanup() {
    print_message "\n🛑 正在停止服务..." $YELLOW
    if [ ! -z "$BACKEND_PID" ]; then
        kill $BACKEND_PID 2>/dev/null || true
        print_message "✅ 后端服务已停止" $GREEN
    fi
    if [ ! -z "$FRONTEND_PID" ]; then
        kill $FRONTEND_PID 2>/dev/null || true
        print_message "✅ 前端服务已停止" $GREEN
    fi
    print_message "👋 服务已全部停止" $BLUE
    exit 0
}

# 设置信号处理
trap cleanup SIGINT SIGTERM

print_title "🚀 文档转换器 - 一键启动脚本"

# 检查必要的命令
print_message "🔍 检查系统环境..." $BLUE
check_command "python3"
check_command "node"
check_command "npm"

# 检查项目结构
print_message "📁 检查项目结构..." $BLUE
check_file "run.py"
check_file "requirements.txt"
check_file "config.yaml"
check_directory "backend"
check_directory "frontend"
check_file "frontend/package.json"

print_message "✅ 环境检查通过" $GREEN

# 读取配置文件
print_message "📖 读取配置文件..." $BLUE
read_config
print_message "✅ 配置读取成功: ${SERVER_HOST}:${SERVER_PORT}:${FRONTEND_HOST}:${FRONTEND_PORT}" $GREEN

# 安装Python依赖
print_title "📦 安装Python依赖"
if [ ! -f ".venv/bin/activate" ]; then
    print_message "🔧 创建Python虚拟环境..." $YELLOW
    python3 -m venv .venv
fi

print_message "🔧 激活虚拟环境..." $YELLOW
source .venv/bin/activate

print_message "📥 安装Python依赖..." $YELLOW
pip install -r requirements.txt

# 安装Node.js依赖
print_title "📦 安装Node.js依赖"
cd frontend
if [ ! -d "node_modules" ]; then
    print_message "📥 安装Node.js依赖..." $YELLOW
    npm install
else
    print_message "✅ Node.js依赖已存在" $GREEN
fi
cd ..

# 启动后端服务
print_title "🖥️  启动后端服务"
print_message "🚀 启动Flask服务器..." $YELLOW
python3 run.py --host ${SERVER_HOST} --port ${SERVER_PORT} &
BACKEND_PID=$!
print_message "✅ 后端服务已启动 (PID: $BACKEND_PID)" $GREEN
print_message "🌐 后端地址: http://${SERVER_HOST}:${SERVER_PORT}" $CYAN

# 等待后端启动
sleep 3

# 启动前端服务
print_title "🎨 启动前端服务"
print_message "🚀 启动Vite开发服务器..." $YELLOW
cd frontend
VITE_PORT=$FRONTEND_PORT npm start &
FRONTEND_PID=$!
cd ..
print_message "✅ 前端服务已启动 (PID: $FRONTEND_PID)" $GREEN
print_message "🌐 前端地址: http://${FRONTEND_HOST}:${FRONTEND_PORT}" $CYAN

# 显示服务信息
print_title "🎉 服务启动完成"
show_service_info
print_message "\n💡 提示:" $BLUE
print_message "   - 按 Ctrl+C 停止所有服务" $BLUE
print_message "   - 前端会自动代理API请求到后端" $BLUE
print_message "   - 修改代码后前端会自动热重载" $BLUE
print_message "   - 服务器配置来自 config.yaml 文件" $BLUE

# 等待用户中断
print_message "\n⏳ 服务运行中... 按 Ctrl+C 停止" $YELLOW
wait

show_service_info() {
    print_message "📍 后端API: http://${SERVER_HOST}:${SERVER_PORT}" $PURPLE
    print_message "📍 前端界面: http://${FRONTEND_HOST}:${FRONTEND_PORT}" $PURPLE
    print_message "📍 健康检查: http://${SERVER_HOST}:${SERVER_PORT}/api/health" $PURPLE
    print_message "📍 API文档: http://${SERVER_HOST}:${SERVER_PORT}/api/docs" $PURPLE
} 